import common from "../../js/common.js"
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    btnStatue:true,
    addname:"点击获取发布位置",
    fileList:[],
    videoUrl:"",
    tapIdx:0,
    latitude:"",
    longitude:""
  },
  //删除图片
  delImg(res){
    console.log(res)
    var idx =res.detail.index
    this.data.fileList.splice(idx,1);
    this.setData({
      fileList:this.data.fileList
    })
  },
  //处理上传图像
  afterReadImg(res){
    console.log(res)
    var oldArr = this.data.fileList
    var newArr = oldArr.concat(res.detail.file)
    this.setData({
      fileList : newArr
    })
  },
  //获取用户位置信息
  getAddress(){
      wx.getSetting({
        success:res=>{
          if(res.authSetting['scope.userLocation'])
          {
              this.openMap();
          }else
          {
             wx.authorize({
               scope: "scope.userLocation",
               success:res=>{
                 this.openMap();
               },
               fail:err=>{
                var userAdd = wx.getStorageSync('userAdd')
                if(userAdd){
                  this.getUserLocation()
                }
                  wx.setStorageSync('userAdd', true)
               }
             })
          }
        }
      })
  },
  //当拒绝了以后重新请求授权
  getUserLocation(){
    wx.getSetting({
      success:res=>{
        if(!res.authSetting['scope.userLocation'])
        {
          wx.showModal({
            title:'是否授权获取当前位置',
            content:'只有获取当前位置才能进行操作',
            success:res=>{
              if(res.confirm){
                wx.openSetting({
                  success:res=>{
                    if(res.authSetting['scope.userLocation']){
                      wx.showToast({
                        title: '授权成功',
                        icon: "success"
                      })
                      setTimeout(()=>{
                         this.openMap()
                      },1000)
                     
                    }
                  }
                })
              }
            }
          })
        }
      }
    })
  },
  //打开地图
    openMap()
     {
      wx.chooseLocation({
        success: (res) =>{
          this.setData({
            addName:res.name,
            latitude:res.latitude,
            longitude:res.longitude
          })
          },
      })
     },
     //检测到用户输入内容激活提交按钮
    onChange(e){
    var val = e.detail
    if(val.length>0)
    {
      this.setData({
        btnStatue:false
      })
    }
    else{
      this.setData({
        btnStatue:true
      })
    }
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
       this.setData({
        tapIdx :options.tapIdx
       })
    
  },

  
 

  //提交表单
    onSubmit(res){
      wx.showLoading({
        mask:true,
        title: '数据提交中...',
      })
      var content = res.detail.value.content
      var addname= this.data.addName
      var latitude = this.data.latitude
      var longitude =this.data.longitude
      var userInfo = app.globalData
      // 获取手机型号
      var phone  = wx.getSystemInfoSync().model
      var subData={
        content,
        addname,
        phone,
        userInfo,
        longitude,
        latitude,
      }
      var { fileList,videoUrl}=this.data
      var d=new Date();
      var year=d.getFullYear();
      var month=d.getMonth()+1
      var day=d.getDate();
      month = month < 10 ? "0" + month : month + ""
      day = day < 10 ? "0" + day : day+""
      var newDate = year+month+day;
      if(fileList.length>0)
      {
        var uploading=fileList.map((item,idx)=>{
          return this.uploadFilePromise("submit_image/" + newDate + "/" + 
          common.guid() + 
          common.gHz(item.url),item)
        })
          Promise.all(uploading).then(res=>{
            var newFileArr = res.map(item=>{
              return item.fileID
            })
            subData.imgUrl = newFileArr  
            this.pushCloud(subData)
          })
          return ;
      }
      if(videoUrl)
      {
        var videoPromise= this.uploadFilePromise("submit_video/" + newDate + "/" + 
          common.guid() + 
          common.gHz(videoUrl),
          {url:videoUrl})
          videoPromise.then(res=>{
            var videoSrc = res.fileID
            subData.videoSrc=videoSrc
            this.pushCloud(subData)
          })
          return;
      }
       this.pushCloud(subData)//纯文字
       wx.hideLoading()
    },
    //上传文件传参
    uploadFilePromise(fileName, chooseResult) {
      return wx.cloud.uploadFile({
        cloudPath: fileName,
        filePath: chooseResult.url
      })
    },

    //点击上传视频按钮
    afterReadVideo(res){
     
      this.setData({
        videoUrl:res.detail.file.url
      })
    },
    //删除视频
    closeVideo(){
      this.setData({
        videoUrl:""
      })
    },

//上传到云存储
    pushCloud(subData){
      wx.cloud.callFunction({
        name:"xiangcun_trSubmit_idea_add",
        data: subData,
        success:res=>{
            wx.hideLoading()
            if(res.result.errCode==87014)
            {
              wx.showToast({
                title: '发布内容不符合规范!',
                icon:"none"
              })
              return ;
            }
            
            this.showToast();
        }
      })
    },
//提示模块
    showToast(){
      wx.showToast({
        title: '发布成功',
        duration:1000
      })
        setTimeout(()=>{
          var indexPages = getCurrentPages()[1]
          indexPages.setData({
            dataList:[]
          })
          indexPages.getpageData()
         
            wx.navigateBack()
        
        },1000)
    },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})